package com.wetool.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import com.wetool.Constant;

@Component
public class BillNoUtils {
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	  /**
     * 重写生成出入库
     * 
     * @param warehouseOptType
     * @return
     * String
     * 
     * @备注， 未做异常处理！
     */
    public synchronized  String getBillNo(byte warehouseOptType,Long shopId) {
        Long seq = null;
        String typeBegin = null;
        try {
            if (warehouseOptType == Constant.WARE_IN) {
                typeBegin = Constant.FLAG_IN;
                seq = getOrderSerial(redisTemplate,typeBegin+getDay()+shopId.toString());
                return getWarehouseNo(typeBegin,seq);
            }
            else if (warehouseOptType == Constant.WARE_OUT) {
            	 typeBegin = Constant.FLAG_OUT;
                 seq = getOrderSerial(redisTemplate,typeBegin+getDay());
                 return getWarehouseNo(typeBegin,seq);
            }
              
        }
       catch (Exception e) {
            // 异常设置8888
            seq = 8888L;
            //logger.error(e.getMessage(), e);
       }
        return null;
    }
	
	/**
	 * 出库入库单号 2位类型+ 年月日（6位）+2位随机数+自增量（4位）;
	 * 
	 * @return String
	 */
	public static String getWarehouseNo(String orderTypeBegin, Long seq) {
		String seqto = String.format("%04d", seq);
		return orderTypeBegin + getDay() + String.format("%02d", (int) (Math.random() * 100)) + seqto;
	}
	 /**
     * 得到现在时间
     * 
     * @return 字符串 yyMMdd
     */
    public static String getDay() {
        Date currentTime = new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
    
    /**
	 * 获取订单号自增长序列，key的格式：orderNO20170510 value:自增序列
	 * @param redisTemplate
	 * @param key 存入redis的key
	 * @return 返回自增长序列
	 */
	public static Long getOrderSerial(RedisTemplate<String, String> redisTemplate, String key){
		ValueOperations<String, String> vo = redisTemplate.opsForValue();
		//设置每次增加1
		Long result = vo.increment(key, 1);
		//设置超过2天自动清除
		redisTemplate.expire(key, 2, TimeUnit.DAYS);
		return result;
	}
}
